#pragma once
#include <arpa/inet.h>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include "Common.hpp"

class InetAddr { // 实现网络地址和本地地址之间的转换
public:
    InetAddr() {}
    // 网络转成主机
    InetAddr(struct sockaddr_in& addr) : _addr(addr) {
        // _ip = inet_ntoa(_addr.sin_addr); 旧接口
        char ipbuffer[128];
        inet_ntop(AF_INET, &addr.sin_addr, ipbuffer, sizeof(ipbuffer));
        _ip = ipbuffer;
        _port = ntohs(_addr.sin_port);
    }
    // 主机转成网络 
    InetAddr(const std::string& ip, uint16_t port) : _ip(ip), _port(port) {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
        _addr.sin_port = htons(port);
    }
    // 主机转成网络
    InetAddr(uint16_t port) : _port(port), _ip() {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_addr.s_addr = INADDR_ANY;
        _addr.sin_port = htons(_port);
    }
    // 设置进去地址，accept上来的对端（客户端的结构）,所以这里是网络转成主机
    void SetAddr(struct sockaddr_in& addr) {
        _addr = addr;
        _port = ntohs(addr.sin_port);
        char buffer[128];
        inet_ntop(AF_INET, &_addr.sin_addr, buffer, sizeof(_addr));
        _ip = buffer;
    }
    uint16_t Port() {
        return _port;
    }
    std::string Ip() {
        return _ip;
    }   
    const struct sockaddr_in& NetAddr() {
        return _addr;
    }
    const struct sockaddr* NetAddrPtr() {
        return CONV(_addr);
    }
    socklen_t NetAddrLen() {
        return sizeof(_addr);
    }
    bool operator==(const InetAddr& ia) {
        return ia._ip == _ip && ia._port == _port;
    }
    std::string StringAddr() const {
        return _ip + ":" + std::to_string(_port);
    }
    ~InetAddr() { }
private:
    struct sockaddr_in _addr;
    std::string _ip;
    uint16_t _port;
};              